package com.atguigu.tingshu.handler;

import com.atguigu.tingshu.entity.CDCEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

@Slf4j
@Component
@CanalTable("album_info") // 监听变更表
public class AlbumInfoCdcHandler implements EntryHandler<CDCEntity> {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 监听到新增数据
     *
     * @param cdcEntity 新增数据
     */
    @Override
    public void insert(CDCEntity cdcEntity) {
        EntryHandler.super.insert(cdcEntity);
    }

    /**
     * 监听到数据修改
     *
     * @param before 修改前数据
     * @param after 修改后数据
     */
    @Override
    public void update(CDCEntity before, CDCEntity after) {
        log.info("监听到数据修改,ID:{}", after.getId());
        // 只要有更新，则会执行当前这个方法
        System.out.println("before:\t" + before.getId());
        System.out.println("after:\t" + after.getId());
        String key = "album:info:[" + after.getId() + "]";
        try {
            // canal底层会维护这一个队列！对于每一个写操作都有顺序性！保证不会乱序！
            this.redisTemplate.delete(key);
        } catch (Exception e) {
            // 发送消息到队列；监听到异常，就进行重试3次 -- 记录消息异常记录表！
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听到数据删除
     *
     * @param cdcEntity 删除前数据
     */
    @Override
    public void delete(CDCEntity cdcEntity) {
        log.info("监听到数据删除,ID:{}", cdcEntity.getId());
        String key = "album:info:" + cdcEntity.getId();
        redisTemplate.delete(key);
    }

}
